package com.turbo.cloud.starter.feign;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * Feign增加配置传递http Header 属性：Authorization
 * @author zhangluning
 *
 * @Configuration 注解加上就会全局生效，有其他情况我们不要用传递Authorization
 */
public class FeignConfiguration implements RequestInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER);
        if(StrUtil.isNotBlank(authorizationHeader)) {
            requestTemplate.header(AUTHORIZATION_HEADER, authorizationHeader);
        }
    }
}
